﻿using System.Collections.Generic;
using IDAL;
using Model;
using NHibernate;

namespace SqlDALLibrary
{
    public class UserActionDal : IUserActionDAL
    {
        private static EntityControl control;

        static UserActionDal()
        {
            control = EntityControl.CreateEntityControl("Model");
        }

        public void saveUserAction(UserAction userAction)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(userAction);
                tx.Commit();
            }
            session.Close();
        }

        public void delUserAction(UserAction userAction)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Delete(userAction);
                tx.Commit();
            }
            session.Close();
        }

        public IList<UserAction> getUserAction(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<UserAction> userActionList = session.CreateQuery("from UserAction ua where ua.user=:user")
                    .SetParameter("user", user)
                    .List<UserAction>();
            session.Close();
            return userActionList;
        }

        public UserAction getUserAction(User user, int actionId)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            UserAction ua = session
                    .CreateQuery("from UserAction ua where ua.user=:user and ua.actionId=:actionId")
                    .SetParameter("user", user)
                    .SetInt32("actionId", actionId)
                    .UniqueResult<UserAction>();
            session.Close();
            return ua;
        }

        public void deleteUserAction(User u)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            session.CreateQuery("delete UserAction where user=:user")
                    .SetParameter("user", u);
            session.Close();
        }

    }
}
